<template>
  <div class='container'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <div class="text item">
        <el-form ref="addQuestionForm" :model="addQuestionForm" :rules="addQuestionRules" label-width="100px">
          <el-form-item label="学科:" prop="subjectID">
            <el-select v-model="addQuestionForm.subjectID" placeholder="请选择">
              <el-option v-for="subject in subjectsList" :key="subject.id" :label="subject.subjectName" :value="subject.id" @click.native="getDirectorys(subject.id)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select v-model="addQuestionForm.catalogID" placeholder="请选择">
              <el-option v-for="directory in directoryList" :key="directory.id" :label="directory.directoryName" :value="directory.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select v-model="addQuestionForm.enterpriseID" placeholder="请选择">
              <el-option v-for="company in companysList" :key="company.id" :label="company.company" :value="company.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="city">
            <el-select v-model="addQuestionForm.province" placeholder="请选择" class="city_left">
              <el-option v-for="(provincesCity,provincesCityIndex) in provincesCityList" :key="provincesCityIndex" :label="provincesCity" :value="provincesCity" @click.native="getAllSubCitys(provincesCity)"></el-option>
            </el-select>
            <el-select v-model="addQuestionForm.city" placeholder="请选择" class="city_right">
              <el-option v-for="(subCity,subCityIndex) in subCitys" :key="subCityIndex" :label="subCity" :value="subCity"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select v-model="addQuestionForm.direction" placeholder="请选择">
              <el-option v-for="(direction,directionIndex) in directions" :key="directionIndex" :label="direction" :value="direction"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:">
            <el-radio-group v-model="addQuestionForm.questionType" @click.native="clearCheckbox">
              <el-radio label="1" @click.native="initRadio">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:">
            <el-radio-group v-model="addQuestionForm.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <quill-editor ref="myTextEditor" v-model="addQuestionForm.question" :options="editorOption" style="height:600px;"></quill-editor>
          </el-form-item>
          <!-- 单选 -->
          <el-form-item label="选项:" class="remarks" v-if="addQuestionForm.questionType === '1'">
            <el-row class="choses" v-for="(option,optionIndex) in addQuestionForm.options" :key="optionIndex">
                  <el-col :span="1">
                    <el-radio-group v-model="option.isRight" >
                      <el-radio :label="true" @click.native="changeIsRight(optionIndex)">{{option.code}}</el-radio>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="6">
                    <el-input v-model="option.title"></el-input>
                  </el-col>
                  <el-col :span="1">
                    <el-tag
                    closable
                    @close="handleClose(tag)"
                    @click="chooseImage(optionIndex)">
                      上传图片
                    </el-tag>
                  </el-col>
                  <input type="file" hidden ref="imageFile" @change="getImage(optionIndex)">
            </el-row>
            <el-button class="addBtn" type="danger" disabled>+添加选项与答案</el-button>
          </el-form-item>
          <!-- 多选 -->
          <el-form-item label="选项:" class="remarks" v-if="addQuestionForm.questionType === '2'">
            <el-row class="choses" v-for="(option,optionIndex) in addQuestionForm.options" :key="optionIndex">
                  <el-col :span="1">
                    <el-checkbox-group v-model="option.multiple">
                      <el-checkbox name="type" label="1" @click.native="changeMutiple(optionIndex)">{{option.code}}</el-checkbox>
                    </el-checkbox-group>
                  </el-col>
                  <el-col :span="6">
                    <el-input v-model="option.title"></el-input>
                  </el-col>
                  <el-col :span="1">
                    <el-tag
                    closable
                    @close="handleClose(tag)"
                    @click="chooseImage(optionIndex)">
                      上传图片
                    </el-tag>
                  </el-col>
                  <input type="file" hidden ref="imageFile"  @change="getImage(optionIndex)">
            </el-row>
            <el-button class="addBtn" type="danger" @click="addChose">+添加选项与答案</el-button>
          </el-form-item>
          <el-form-item label="解析视频:" class="video" prop="videoURL">
            <el-input v-model.trim="addQuestionForm.videoURL"></el-input>
          </el-form-item>
           <el-form-item label="答案解析:" prop="answer">
            <quill-editor ref="myTextEditor" v-model="addQuestionForm.answer" :options="editorOption" style="height:600px;"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注:" class="remarks" prop="remarks">
            <el-input class="remarkstextarea" type="textarea" v-model="addQuestionForm.remarks" size="large"></el-input>
          </el-form-item>
          <el-form-item label="试题标签:" class="questionTag">
            <el-select v-model="addQuestionForm.tags" multiple placeholder="请选择活动区域">
              <el-option v-for="(tag,tagIndex) in tagsList" :key="tagIndex" :label="tag.tagName" :value="tag.tagName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('addQuestionForm')" v-if="!$route.query.id">立即创建</el-button>
            <el-button type="success" @click="submitForm('addQuestionForm')" v-else>确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script src="@/base/map.json"></script>
<script>
// 学科列表
import {list as subjectListAPI} from '@/api/hmmm/subjects.js'

// 目录列表
import {list as directoryListAPI} from '@/api/hmmm/directorys.js'

// 企业列表
import {list as companysListAPI} from '@/api/hmmm/companys.js'

// 所有城市、城市下地区
import {provinces,citys} from '@/api/hmmm/citys.js'

// 方向
import {direction} from '@/api/hmmm/constants.js'

// 标签列表
import {list as tagList} from '@/api/hmmm/tags.js'

// 基础题库添加、基础题库详情、基础题库修改
import {add,detail,update} from '@/api/hmmm/questions.js'

import {mapState} from 'vuex'
export default {
  name:'questionNew',
  data(){
    // 正则验证
    var checkVideoUrl = (rule,value,callback) => {
      var regVideo = /^https?.+\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4)$/i
        if(!regVideo.test(value)) {
          callback(new Error('视频URL格式错误'))
        }else {
          callback()
        }
    }
    return {
      // 试题录入表单
      addQuestionForm: {
        // 学科
        subjectID:'',
        // 目录
        catalogID:'',
        // 企业
        enterpriseID:'',
        // 城市
        province:'',
        // 地区
        city:'',
        // 方向
        direction:'',
        // 题型
        questionType:'1',
        // 难度
        difficulty:'1',
        // 题干
        question:'',
        // 单选选项
        options: [
          {
            code:String.fromCharCode(65),
            title:'',
            img:'',
            isRight:false,
            multiple:false
          },
          {
            code:String.fromCharCode(66),
            title:'',
            img:'',
            isRight:false,
            multiple:false
          },
          {
            code:String.fromCharCode(67),
            title:'',
            img:'',
            isRight:false,
            multiple:false
          },
          {
            code:String.fromCharCode(68),
            title:'',
            img:'',
            isRight:false,
            multiple:false
          }

        ],
        // 解析视频
        videoURL:'',
        // 备注
        remarks:'',
        // 试题标签
        questionTag:'',
        // 单选选项
        singletype:'',
        // 多选选项
        chosetype:[],
        // 试题标签
        tags:[],
        // 答案解析富文本编辑器
        answer: '',
      },
      // 试题录入表单规则
      addQuestionRules: {
remarks: [
          { required: true, message: '请输入备注', trigger: 'change' }
        ],
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' },
        ],
        enterpriseID:[
          { required: true, message: '请选择企业', trigger: 'change' },
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' },
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' },
        ],
        question: [
          { required: true, message:'请输入题干', trigger: 'blur' },
        ],
        answer: [
          { required: true, message:'请输入答案', trigger: 'blur' },
        ],
        videoURL: [
          { validator: checkVideoUrl, required:false , trigger: 'blur' }
        ],
      },
      editorOption: {
        placeholder: '',
        modules:{
          toolbar:[
            ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],     //列表
            ['blockquote', 'code-block'],     //引用，代码块
            ['link'],
            ['image']    //上传图片、上传视频
          ]
        }
      },
      // 学科下拉框数据
      subjectsList:[],
      // 目录下拉框数据
      directoryList:[],
      // 企业下拉框数据
      companysList:[],
      // 所有主城市数据
      provincesCityList:[],
      // 主要城市下辖区
      subCitys:[],
      // 方向下拉框数据
      directions:[],
      // ascii码表示字符
      asciiIndex: 69,
      // 标签选项
      tagsList:[],
    }
  },
  methods:{
    onEditorChange({ editor, html, text }) {
      this.content = html;
    },
    // 删除图片
    handleClose(tag) {
      console.log('删除图片');
    },
    // 选择图片
    chooseImage(index) {
      this.$refs.imageFile[index].click()
    },
    // 获取学科列表
    async getSubjectList() {
      try {
        const {data:res} = await subjectListAPI({
          pagesize:20
        })
        this.subjectsList = res.items
      }catch(err) {
        console.log(err);
      }
    },
    // 获取企业目录
    async getCompanysList() {
      try {
        const {data:res} = await companysListAPI()
        this.companysList = res.items
      }catch(err) {
        console.log(err);
      }
    },
    // 通过学科获取目录和标签
    async getDirectorys(subjectId) {
      this.addQuestionForm.catalogID = ''
      this.addQuestionForm.tags = []
      try {
        const {data:res} = await directoryListAPI({
        subjectID:subjectId
        })
        this.directoryList = res.items
        this.getTagsList({
          subjectID:subjectId
        })
      }catch(err) {
        console.log(err);
      }

    },
    // 获取所有城市
    async getAllProvincesCitys() {
      try {
        const data = await provinces()
        this.provincesCityList = data
      }catch(err) {
        console.log(err);
      }
    },
    // 获取城市下辖区
    async getAllSubCitys(provincesCity) {
      try {
        this.addQuestionForm.city = ''
        const data = await citys(provincesCity)
        this.subCitys = data
      }catch(err) {
        console.log(err);
      }

    },
    // 添加选项
    addChose() {
      const newChoose = {
            code:String.fromCharCode(this.asciiIndex++),
            title:'',
            img:'',
            isRight:'0',
            multiple:false
          }
      this.addQuestionForm.options.push(newChoose)
    },
    // 得到图片
    getImage(optionIndex) {
      console.log(this.$refs.imageFile[optionIndex].files);
    },
    // 改变isRight
    changeIsRight(optionIndex) {
      console.log(optionIndex);
      console.log(this.addQuestionForm.options);
      this.addQuestionForm.options.forEach((item,index) => {
        item.isRight = false
        if(index === optionIndex) {
          item.isRight = true
        }
      })
    },
    // 通过改变多选mutiple改变isRight
    changeMutiple(optionIndex) {
      if(this.addQuestionForm.options[optionIndex].multiple) {
        this.addQuestionForm.options[optionIndex].isRight = false
      }else {
        this.addQuestionForm.options[optionIndex].isRight = true
      }
    },
    // 重置选项框
    clearCheckbox() {
      this.addQuestionForm.options.forEach(item => {
        item.isRight = false
        item.multiple = false
      })
    },
    // 重置单选框
    initRadio() {
      const newDate = this.addQuestionForm.options.slice(0,4)
      this.addQuestionForm.options = newDate
    },
    // 获取标签
    async getTagsList(subjectID) {
      const {data:res} = await tagList(subjectID)
      this.tagsList = res.items
    },
    // 提交表单
    submitForm() {
      this.$refs.addQuestionForm.validate((async valid => {
        if(valid) {
          try {
            this.addQuestionForm.tags = this.addQuestionForm.tags.join()
            if(this.$route.query.id) {
              this.addQuestionForm.id = parseInt(this.$route.query.id)
              const data = await update(this.addQuestionForm)
              this.$message.success('修改成功')
            }else {
              await add(this.addQuestionForm)
              this.$message.success('添加成功')
            }
            if(this.$route.query.id) {
              this.$router.back()
            }else {
              this.$router.push('/questions/list')
            }
          }catch(err) {
            this.$router.go(0)
          }
        }else {
          return false
        }
      }))
    },
    // 获取基础题库详情
    async getQuestionDetail() {
      if(!this.$route.query.id) {
        return false
      }
      const {data:res} = await detail(this.$route.query)
      res.options.forEach(item => {
        if(item.isRight === 1) {
          item.isRight = true
          item.multiple = true
        }else {
          item.isRight = false
          item.multiple = false
        }
      })
      res.tags = res.tags.split(',')
      this.getDirectorys(res.subjectID)
      this.addQuestionForm = res
    }
  },
  computed: {
    ...mapState['beforePath']
  },
  created() {
    // 获取学科列表
    this.getSubjectList({
      pagesize:30
    })
    // 获取企业目录
    this.getCompanysList()
    // 获取所有城市
    this.getAllProvincesCitys(),
    // 获取方向列表数据
    this.directions = direction
    // 获取基础题库详情
    this.getQuestionDetail()
  },
}
</script>

<style scoped lang="scss">
.container {
  .box-card {
    .el-select {
      width: 45%;
      margin-right: 1%;
    }
    .city_left {
      width: 22%;
    }
    .city_right {
      width: 22%;
    }
  }
  .quill-editor {
    height: 300px !important;
    margin-bottom: 50px;
  }
  ::v-deep .remarks {
    .remarkstextarea {
      width: 500px;
      textarea.el-textarea__inner {
        height: 100px !important;
      }
    }
    .el-tag {
      position: relative;
      left: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 50px;
      width: 100px;
      background: none;
      color: #000;
      border:1px dashed #ccc;
      cursor: pointer;
    .el-tag__close {
      position: absolute;
      top: -8px;
      right: -6px;
      font-size: 20px;
      color: #000;
      &::before {
        content:'\e78d';
        color:#ccc;
        background-color: #fff;
      }
    }
  }
  }
  .choses {
    margin-bottom: 10px;
  }
  .addBtn {
    margin-top: 20px;
  }
  .video {
    .el-input {
      width: 45%;
    }
  }
  .el-row {
    display: flex;
    align-items: center;
  }
}
</style>
